package com.dz.lm.service.userproduct.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dz.lm.common.dto.*;
import com.dz.lm.common.exception.DaoException;
import com.dz.lm.common.exception.ServiceException;
import com.dz.lm.common.util.DzCache;
import com.dz.lm.common.util.StringUtil;
import com.dz.lm.common.util.TecentVideo;
import com.dz.lm.common.utils.DateUtil;
import com.dz.lm.common.utils.StringUtils;
import com.dz.lm.dao.account.write.AccountDao;
import com.dz.lm.dao.agentreview.read.AgentReviewDao;
import com.dz.lm.dao.appLogin.read.AppLoginDao;
import com.dz.lm.dao.compproduct.read.CompProductDao;
import com.dz.lm.dao.compuser.read.CompUserDao;
import com.dz.lm.dao.order.write.OrderDao;
import com.dz.lm.dao.product.read.CommonAreaDao;
import com.dz.lm.dao.userproduct.write.UserProductDao;
import com.dz.lm.domain.compproduct.CompProduct;
import com.dz.lm.domain.compuser.CompUser;
import com.dz.lm.domain.compuser.CompUserExample;
import com.dz.lm.domain.order.Order;
import com.dz.lm.domain.product.CommonArea;
import com.dz.lm.domain.userapply.UserApplyExample;
import com.dz.lm.domain.usercollection.UserCollection;
import com.dz.lm.domain.usercollection.UserCollectionExample;
import com.dz.lm.domain.userproduct.UserProduct;
import com.dz.lm.domain.userproduct.UserProductExample;
import com.dz.lm.service.agentreview.AgentReviewService;
import com.dz.lm.service.attach.AttachService;
import com.dz.lm.service.useragent.UserAgentService;
import com.dz.lm.service.userapply.UserApplyService;
import com.dz.lm.service.userproduct.UserProductService;
import com.dz.lm.service.usersend.UserSendService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.gson.JsonObject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import springfox.documentation.spring.web.json.Json;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.*;

/**
 * @version 1.8;
 * @author: LDY;
 * @Description;
 * @Date: Created in 2020/3/8 12:41;
 */
@Service("userProductService")
public class UserProductServiceImpl implements UserProductService {
    @Resource(name = "readCompProductDao")
    private CompProductDao readCompProductDao;
    @Resource(name = "writeUserProductDao")
    private UserProductDao writeUserProductDao;
    @Resource(name = "readUserProductDao")
    private com.dz.lm.dao.userproduct.read.UserProductDao readUserProductDao;
    @Resource(name = "readAppLoginDao")
    private AppLoginDao rAppLoginDao;
    @Autowired
    private UserAgentService userAgentService;
    @Autowired
    private UserApplyService userApplyService;
    @Autowired
    private AttachService attachService;
    @Resource(name = "readUserApplyDao")
    private com.dz.lm.dao.userapply.read.UserApplyDao readUserApplyDao;
    @Autowired
    private CommonAreaDao readCommonAreaDao;
    @Resource(name = "readUserCollectionDao")
    private com.dz.lm.dao.usercollection.read.UserCollectionDao readUserCollectionDao;
    @Resource(name = "readUserAgentDao")
    private com.dz.lm.dao.useragent.read.UserAgentDao readUserAgentDao;
    @Resource
    private com.dz.lm.dao.account.read.AccountDao readAccountDao;
    @Resource
    private OrderDao writeOrderDao;
    @Resource
    private AccountDao writeAccountDao;
    @Autowired
    private UserSendService userSendService;
    @Autowired
    private AgentReviewService agentReviewService;
    @Resource(name = "readCompUserDao")
    private CompUserDao readCompUserDao;

    @Override    @Transactional
    public int add(UserProduct product) throws ServiceException {
        int ret = 0;
        try {
            ret = writeUserProductDao.insertSelective(product);
            if (ret > 0) {
                ret = product.getProductId();
            }
        } catch (DaoException e) {
            e.printStackTrace();
        }
        return ret;
    }

    @Override
    public int update(UserProduct product) throws ServiceException {
        int ret = 0;
        try {
            ret = writeUserProductDao.updateByPrimaryKeySelective(product);
        } catch (DaoException e) {
            e.printStackTrace();
        }
        return ret;
    }
    @Transactional
    @Override
    public int updateImage(Map map) throws ServiceException {
        int ret = 0;
        int productId = StringUtil.getInt(map.get("productId"), 0);
        try {
            UserProduct userProduct = readUserProductDao.selectByPrimaryKey(productId);
            if (userProduct == null) {
                return ret;
            }
            String name = StringUtil.getString(map.get("name"));
            switch (name) {
                case "image_url1":
                    String image_url1 = StringUtil.getString(map.get("image_url1"));
                    if (!StringUtil.containEmpty(image_url1)) {
                        userProduct.setImageUrl1(image_url1);
                    }
                    break;
                case "image_url2":
                    String image_url2 = StringUtil.getString(map.get("image_url2"));
                    if (!StringUtil.containEmpty(image_url2)) {
                        userProduct.setImageUrl2(image_url2);
                    }
                    break;
                case "image_url3":
                    String image_url3 = StringUtil.getString(map.get("image_url3"));
                    if (!StringUtil.containEmpty(image_url3)) {
                        userProduct.setImageUrl3(image_url3);
                    }
                    break;
                case "image_url4":
                    String image_url4 = StringUtil.getString(map.get("image_url4"));
                    if (!StringUtil.containEmpty(image_url4)) {
                        userProduct.setImageUrl4(image_url4);
                    }
                    break;
                case "image_url5":
                    String image_url5 = StringUtil.getString(map.get("image_url5"));
                    if (!StringUtil.containEmpty(image_url5)) {
                        userProduct.setImageUrl5(image_url5);
                    }
                    break;
            }
            ret = writeUserProductDao.updateByPrimaryKeySelective(userProduct);
        } catch (DaoException e) {
            e.printStackTrace();
        }

        return ret;
    }
    @Transactional
    @Override
    public PageDto query(int pageNum, int rows, int uid, int userId, int source, String search, int type, int status, String province, String city, int orderType) throws ServiceException {
        if (orderType == 1) { //orderType 为1 是推荐首页
            return this.Recommend(pageNum, rows, uid, type, province, city);
        }
        PageDto pageDto = new PageDto();
        UserProductExample ex = new UserProductExample();
        UserProductExample.Criteria cr = ex.createCriteria();
        if (userId > 0) {
            cr.andUserIdEqualTo(userId);
        } else {

            ex.setUid(uid);
        }
        switch (orderType) {
            case 0://默认 收藏和发布时间
                UserCollectionExample example = new UserCollectionExample();
                UserCollectionExample.Criteria criteria = example.createCriteria();
                criteria.andUserIdEqualTo(uid);
                criteria.andStatusEqualTo(1);
                criteria.andTypeEqualTo(1);
                try {
                    List<UserCollection> userCollections = readUserCollectionDao.selectByExample(example);
                    if (userCollections != null && userCollections.size() > 0) {
                        StringBuilder builder = new StringBuilder();
                        for (UserCollection collection : userCollections) {
                            builder.append(collection.getObjId()).append(",");
                        }
                        String cOrder = builder.toString().substring(0, builder.toString().length() - 1);
                        ex.setOrderByClause("field(product_id," + cOrder + ") DESC ,create_time DESC");

                    } else {
                        ex.setOrderByClause("update_time DESC");
                    }
                } catch (DaoException e) {
                    e.printStackTrace();
                }
                break;
            case 1://申请数量
                ex.setOrderByapply(true);
                break;
            case 2://发布时间
                ex.setOrderByClause("update_time DESC");
                break;
        }


        if (source > 0) {
            cr.andSourceEqualTo(source);
        }
        if (!StringUtils.isEmpty(search)) {
            cr.andProductNameLike("%"+search + "%");
        }
        if (type > 0) {
            cr.andProductTypeEqualTo(type);
        }
        if (status > 0) {
            cr.andStatusEqualTo(status);
        } else {
            cr.andStatusNotEqualTo(3);//删除状态
        }
        if (!StringUtils.isEmpty(province)) {
            cr.andProvinceEqualTo(province);
        }
        if (!StringUtils.isEmpty(city)) {
            cr.andCityEqualTo(city);
        }

        try {
            PageHelper.startPage(pageNum, rows);
            List<UserProduct> userProducts = readUserProductDao.selectByExample(ex);
            if (userProducts != null && userProducts.size() > 0) {
                List<UserProductDTO> dtos = new ArrayList();
                PageInfo info = new PageInfo(userProducts);
                for (UserProduct product : userProducts) {
                    UserProductDTO dto = new UserProductDTO();
                    BeanUtils.copyProperties(product, dto);
                    setExt(dto, uid, false);
                    dtos.add(dto);
                }
                pageDto.setInfo(info);
                pageDto.setList(dtos);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return pageDto;
    }

    @Override
    @Transactional
    public int updateLowe(int productId, int status, String province, String city) throws ServiceException {
        int ret = 0;
        //代理产品
        UserProduct userProduct = new UserProduct();
        userProduct.setProductId(productId);
        userProduct.setStatus(status);
        if (!"100000".equals(province)) { //全国：100000
            userProduct.setProvince(province);
            //全北京 天津 上海 重庆
            if (!"".equals(city) && !"110100".equals(city) && !"120100".equals(city) && !"310100".equals(city) && !"500100".equals(city))
                userProduct.setCity(city);
        }
        try {
            UserProduct product = readUserProductDao.selectByPrimaryKey(productId);
            if (status == 2) { //产品发布时间,
                userProduct.setUpdateTime(DateUtil.getTimeStr(new Date()));
            }
            if (product.getProductType() == 1 && status == -1) { //原生下架后 处理相关代理产品
                //更新代理产品代理状态 2原产品下架
                this.updateAgent(0, productId, 0, 2, 2, -1, -1);
            }
            if (product.getProductType() == 2 && status == 2) { //代理产品发布,获取原生产品,计算代理费
                //判断是否以前代理过该产品
                UserProductExample cEx = new UserProductExample();
                UserProductExample.Criteria cr = cEx.createCriteria();
                cr.andSuperIdEqualTo(product.getSuperId());
                cr.andUserIdEqualTo(product.getUserId());
                int count = readUserProductDao.querCount(cEx);//代理过则不判断代理费逻辑
                //设置代理产品状态,正常代理
                userProduct.setAgentStatus(1);
                UserProduct source = readUserProductDao.selectByPrimaryKey(product.getSuperId());
                   /* UserProductExample px = new UserProductExample();  对于重复代理要不要判断发布
                    UserProductExample.Criteria pr = px.createCriteria();
                    pr.andProductTypeEqualTo(2);
                    pr.andSuperIdEqualTo(source.getProductId());
                    pr.andUserIdEqualTo(pro)*/
                Integer rank = source.getRank();//排名
                Integer grantNum = source.getGrantNum();//发放代理小费排名
                rank = rank + 1;
                source.setRank(rank);
                Double agentCost = source.getAgentCost();//代理小费
                if (agentCost > 0 && rank <= grantNum && product.getRank() == 0 && count <= 1) { //计算代理排名,且此代理产品，未计算过排名
                    //添加代理产品排名
                    userProduct.setRank(rank);
                    Map userInfo = new HashMap();
                    //代理人账户
                    userInfo.put("userId", product.getUserId());
                    Map<String, Object> Uaccount = readAccountDao.qryAccountInfoByUserId(userInfo);
                    userInfo.clear();
                    //原产品人产品人账户
                    userInfo.put("userId", product.getSource());
                    Map<String, Object> Saccount = readAccountDao.qryAccountInfoByUserId(userInfo);

                    //计算代理人的账户金额
                    BigDecimal agentCostB = new BigDecimal(agentCost);
                    BigDecimal amount = new BigDecimal(Uaccount.get("amount").toString());
                    BigDecimal nowAmount = amount.add(agentCostB);
                    BigDecimal cashAmount = new BigDecimal(Uaccount.get("cashAmount").toString());
                    BigDecimal nowCashAmount = cashAmount.add(agentCostB);
                    //代理人账户流水
                    Order order = new Order();
                    String orderId = getOrderId();
                    order.setOrderId(orderId);
                    order.setUserId(Integer.parseInt(Uaccount.get("userId").toString()));
                    order.setAccountId(Integer.valueOf(Uaccount.get("accountId").toString()));
                    order.setAmount(agentCost);
                    order.setGatherAccountId(Integer.valueOf(Saccount.get("accountId").toString()));
                    order.setGatherUserId(Integer.parseInt(Saccount.get("userId").toString()));
                    order.setOrderType("6");//代理费 收入
                    order.setPayType("3");//账户
                    order.setState("13");//冲入
                    writeOrderDao.addOrder(order);
                    //远产品人 账单流水
                       /* Order ordery = new Order();
                        String orderIdy = getOrderId();
                        ordery.setOrderId(orderIdy);
                        ordery.setUserId(Integer.parseInt(Saccount.get("userId").toString()));
                        ordery.setAccountId(Integer.valueOf(Saccount.get("accountId").toString()));
                        ordery.setAmount(agentCost);
                        ordery.setGatherAccountId(Integer.valueOf(Uaccount.get("accountId").toString()));
                        ordery.setGatherUserId(Integer.parseInt(Uaccount.get("userId").toString()));
                        ordery.setOrderType("4");//代理费 支出
                        ordery.setPayType("3");//账户
                        ordery.setState("23");//已完成
                        writeOrderDao.addOrder(ordery);*/
                    //更新账户
                    Uaccount.put("amount", nowAmount);
                    Uaccount.put("cash_amount", nowCashAmount);
                    writeAccountDao.updateAccount(Uaccount);
                    //更新排名
                    writeUserProductDao.updateByPrimaryKeySelective(source);
                }
            }
            //更新代理产品
            ret = writeUserProductDao.updateByPrimaryKeySelective(userProduct);

        } catch (DaoException e) {
            e.printStackTrace();
        }
        return ret;
    }

    @Override
    public UserProductDTO getDetail(int uid, int productId, boolean isDetail) throws ServiceException {
        UserProductDTO dto = new UserProductDTO();
        try {
            UserProduct userProduct = readUserProductDao.selectByPrimaryKey(productId);
            if (userProduct != null) {
                BeanUtils.copyProperties(userProduct, dto);
                if (isDetail) {
                    setExt(dto, uid, true);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return dto;
    }

    //uid当前登录人
    private void setExt(UserProductDTO dto, int uid, boolean isDetail) throws Exception {
        //发布者
        Map p1 = new HashMap();
        p1.put("userId", dto.getUserId());
        Map user = rAppLoginDao.qryUserInfoByUserId(p1);
        //公司标识
        CompUserExample coex = new CompUserExample();
        CompUserExample.Criteria cocr = coex.createCriteria();
        cocr.andUserIdEqualTo(dto.getUserId());
        cocr.andStatusEqualTo(1);
        List<CompUser> compUsers = readCompUserDao.selectByExample(coex);
        if (compUsers != null && compUsers.size() > 0) {
            user.put("compId", compUsers.get(0).getCompId());

        }
        //查询成交量
        int applyedCount = userApplyService.querCount(dto.getUserId(), 0, 0, 0, 0, false, false, false, 0, 0);
        user.put("applyedCount", applyedCount);
        dto.setUser(user);

        //来源信息
        Map sources = new HashMap();
        //来源申请次数
        int sourApplyCount = 0;
        if (dto.getProductType() == 1) {
            sources.putAll(user);
        } else if (dto.getProductType() == 2) {
            //代理产品填充排名
            UserProduct userProduct = readUserProductDao.selectByPrimaryKey(dto.getSuperId());
            dto.setRank(userProduct.getRank());
            Map p2 = new HashMap();
            p2.put("userId", dto.getSource());
            sourApplyCount = userApplyService.querCount(dto.getSource(), 0, 0, 0, 0, false, false, false, 0, 0);
            Map sourceUser = rAppLoginDao.qryUserInfoByUserId(p2);
            sources.putAll(sourceUser);
            sources.put("applyedCount", sourApplyCount);
            //计算代理后 价格
            if (dto.getAgentSale() != null && dto.getAgentSale() > 0) {
                dto.setAgentPrice(new BigDecimal(dto.getPrice()).multiply(new BigDecimal(dto.getAgentSale())).doubleValue() / 10);
            } else if (dto.getPrice() > 0) {
                dto.setAgentPrice(dto.getPrice());
            }
        }
        dto.setSourceProduct(sources);
        //产品的申请次数
        dto.setApplyCount(userApplyService.querCount(0, 0, 0, dto.getProductType() == 1 ? dto.getProductId() : dto.getSuperId(), 0, false, false, false, 0, 0));
        //添加视频信息
        if (dto.getVideoId() > 0) {
            AttachDTO attachDTO = attachService.sleletById(dto.getVideoId());
            if (attachDTO != null) {
                dto.setVideoInfo(attachDTO);
            }
        }
        //adress
        CommonArea province = readCommonAreaDao.selectByPrimaryKey(Integer.parseInt(dto.getProvince()));
        CommonArea city = null;
        if (!StringUtils.isEmpty(dto.getCity())) {
            city = readCommonAreaDao.selectByPrimaryKey(Integer.parseInt(dto.getCity()));
        }
        String provinceName = province != null ? province.getName() : "";
        String cityName = city != null ? city.getName() : "";
        String adress = provinceName + cityName;

        dto.setAddress(adress);
        //多少小时前发布
        Date now = new Date();
        Date up = DateUtil.getDateTimeByDay(dto.getUpdateTime());
        long time = now.getTime() - up.getTime();
        long hours = time / 3600000;
        if (hours >= 24) {
            if (hours > 7200) {
                long l = hours / 24 / 30;
                dto.setTimes(l + "月前");

            } else {
                long l = hours / 24;
                long l1 = hours % 24;
                dto.setTimes(l + "天" + l1 + "小时前");
            }
        } else {
            if (hours < 1) {
                dto.setTimes("刚刚");

            } else {
                dto.setTimes(hours + "小时前");

            }
        }
        //是否收藏
        if (uid > 0) {
            UserCollectionExample ex = new UserCollectionExample();
            UserCollectionExample.Criteria cr = ex.createCriteria();
            cr.andUserIdEqualTo(uid);
            cr.andStatusEqualTo(1);//收藏
            cr.andObjIdEqualTo(dto.getProductId());
            cr.andTypeEqualTo(1);//产品
            List<UserCollection> userCollections = readUserCollectionDao.selectByExample(ex);
            if (userCollections != null && userCollections.size() > 0) {
                dto.setIsCollection(1);
            }
        }
        //是否可代理
        if (dto.getProductType() == 1 && dto.getUserId() != uid) {
            UserProductExample pex = new UserProductExample();
            UserProductExample.Criteria pcr = pex.createCriteria();
            pcr.andUserIdEqualTo(uid);
            pcr.andSuperIdEqualTo(dto.getProductId());
            pcr.andStatusNotEqualTo(3);//删除
            List<Integer> agstatus = new ArrayList();
            agstatus.add(1);//正常代理
            agstatus.add(4);//返点发生变化
            pcr.andAgentStatusIn(agstatus);
            int i = readUserProductDao.querCount(pex);
            if (i == 0) {
                dto.setIsAgent(1);
            } else {
                if (dto.getIsReview() > 0) {
                    int i1 = agentReviewService.queryCount(0, applyedCount, dto.getProductId(), -1);
                    if (i1 == i) {
                        dto.setIsAgent(1);
                    }
                }
            }
        }
        if (isDetail && uid > 0) { //判断是否申请过此产品
            UserApplyExample aex = new UserApplyExample();
            UserApplyExample.Criteria acr = aex.createCriteria();
            acr.andStatusEqualTo(1);//申请中
            acr.andSubUserIdEqualTo(uid);
            if (dto.getProductType() == 1) {
                acr.andProductIdEqualTo(dto.getProductId());
            } else {
                acr.andProductIdEqualTo(dto.getSuperId());
            }
            int i = readUserApplyDao.queryCount(aex);
            if (i > 0) {
                dto.setApplyFlag(1);
            }
        }
        //代理产品未发布，需要审核时，填充审核的信息
        if (dto.getStatus() == 1 && dto.getProductType() == 2 && dto.getIsReview() > 0) {
            AgentReviewDTO reviewDTO = agentReviewService.get(0, dto.getProductId(), true);
            if (reviewDTO != null) {
                dto.setAgentReivew(reviewDTO);
            }
        }
        //填充返点信息,和折扣信息
        if (!StringUtil.containEmpty(dto.getAgentLevel())) {
            JSONArray objects = JSON.parseArray(dto.getAgentLevel());
            if (objects.size() == 1) {
                Map map = (Map) objects.get(0);
                dto.setReturnInfo(map.get("returnPoint").toString() + "%");
                dto.setAgentInfo(map.get("agentSale").toString() + "折");
            } else if (objects.size() > 1) {
                Map map1 = (Map) objects.get(0);
                Map map2 = (Map) objects.get(objects.size() - 1);
                dto.setReturnInfo(map1.get("returnPoint").toString() + "% - " + map2.get("returnPoint") + "%");
                dto.setAgentInfo(map1.get("agentSale").toString() + "折 - " + map2.get("agentSale") + "折");

            }

        }else {
            dto.setReturnInfo( "0%");
            dto.setAgentInfo( "无");
        }
    }
    @Transactional
    @Override
    public UserProductDTO getDeail(int productId, int uid) throws ServiceException {
        UserProductDTO dto = new UserProductDTO();
        try {
            UserProduct product = readUserProductDao.selectByPrimaryKey(productId);
            BeanUtils.copyProperties(product, dto);
            setExt(dto, uid, true);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return dto;
    }
    @Transactional
    @Override
    public int updateAgent(int source, int supProudcId, int productId, int agentStatus, int productType, double returnPoint, double price) throws ServiceException {
        int ret = 0;
        Map map = new HashMap();
        if (source > 0) {
            map.put("source", source);
        }
        if (supProudcId > 0) {
            map.put("supProudcId", supProudcId);
        }
        if (productId > 0) {
            map.put("productId", productId);
        }
        if (agentStatus > 0) {
            map.put("agentStatus", agentStatus);
        }
        if (productType > 0) {
            map.put("productType", productType);
        }
        if (returnPoint > -1) {
            map.put("returnPoint", returnPoint);
        }
        if (price > -1) {
            map.put("price", price);

        }
        map.put("status", 1);
        try {
            map.put("updateTime", com.smartlbs.util.DateUtil.getNowDateTimeString());
        } catch (ParseException e) {
            e.printStackTrace();
        }

        try {
            ret = writeUserProductDao.updateAgent(map);
        } catch (DaoException e) {
            e.printStackTrace();
        }
        return ret;
    }
    @Transactional
    @Override
    public PageDto querSends(int page, int rows, int uid, int status) throws ServiceException {
        PageDto pageDto = new PageDto();
        PageHelper.startPage(page, rows);
        Map map = new HashMap();
        map.put("sendUid", uid);
        map.put("status", status);
        try {
            List<UserProduct> userProducts = readUserProductDao.querSends(map);
            if (userProducts != null && userProducts.size() > 0) {
                List<UserProductDTO> dtos = new ArrayList();
                PageInfo info = new PageInfo(userProducts);
                for (UserProduct product : userProducts) {
                    UserProductDTO dto = new UserProductDTO();
                    BeanUtils.copyProperties(product, dto);
                    setExt(dto, uid, false);
                    dtos.add(dto);
                }
                pageDto.setInfo(info);
                pageDto.setList(dtos);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return pageDto;
    }

    /**
     * 生产订单ID
     */
    private String getOrderId() {
        String orderId = "";
        @SuppressWarnings("unchecked")
        List<String> orderIdList = (List<String>) DzCache.getCacheCode("orderId");
        if (orderIdList != null && orderIdList.get(0) != null) {
            orderId = orderIdList.get(0);
            orderIdList.remove(0);
        } else {
            long todayMaxorderId = DzCache.getCacheCode("todayMaxorderId") == null ? 0l : (long) DzCache.getCacheCode("todayMaxorderId");
            long maxId = todayMaxorderId + 100;
            DzCache.setCacheCode("todayMaxorderId", maxId);
            orderIdList = new ArrayList<String>();
            String strTime = DateUtil.getTimeStrFormat(new Date());
            String suffix = "00000000";
            for (long i = todayMaxorderId + 1; i < maxId + 1; i++) {
                suffix = suffix + "" + i;
                suffix = suffix.substring(suffix.length() - 8, suffix.length());
                orderIdList.add(strTime + "" + suffix);
            }
            orderId = orderIdList.get(0);
            orderIdList.remove(0);
            DzCache.setCacheCode("orderId", orderIdList);
        }
        return orderId;
    }
    @Transactional
    @Override
    public Map getUser(String uId, int userId) throws ServiceException {
        Map p1 = new HashMap();
        int uid = 0;
        if (uId.length() == 32) { //md5加密的id，获取响应的
            Map m = new HashMap();
            m.put("userId", uId);
            try {
                Map map = rAppLoginDao.qryUserIdByMd5UserId(m);
                uid = StringUtil.getInt(map.get("userId"), 0);
            } catch (DaoException e) {
                e.printStackTrace();
            }
        } else {
            uid = StringUtil.getInt(uId, 0);
        }
        p1.put("userId", uid);
        Map user = null;
        try {
            user = rAppLoginDao.qryUserInfoByUserId(p1);
            //查询申请量
            int applyedCount = userApplyService.querCount(uid, 0, 0, 0, 0, true, false, false, 0, 0);
            user.put("applyedCount", applyedCount);
            //查询代理人数
            int agentdCount = userAgentService.queryCount(uid, 0, 0, 1);
            user.put("agentdCount", agentdCount);
            //粉丝数
            UserCollectionExample ex = new UserCollectionExample();
            UserCollectionExample.Criteria cr = ex.createCriteria();
            cr.andTypeEqualTo(2);//用户
            cr.andStatusEqualTo(1);//关注
            cr.andObjIdEqualTo(uid);
            int fansCount = readUserCollectionDao.queryCount(ex);
            user.put("fansCount", fansCount);
            //判断此首页是否关注
            cr.andUserIdEqualTo(userId);
            int focusFlag = readUserCollectionDao.queryCount(ex);
            user.put("focusFlag", focusFlag);
            int applyDot = userApplyService.querCount(uid, 0, 0, 0, 0, true, false, false, 0, 1);
            user.put("applyDot", applyDot);
            //判断此主页用户是否是你的代理人
            int count = userAgentService.queryCount(userId, uid, 0, 1);
            if (count > 0) {
                user.put("isAgent", 1);  //1是代理人 0不是
            } else {
                user.put("isAgent", 0);
            }
            //获取当前人未处理受邀产品,凭借信息
            StringBuilder builder = new StringBuilder();
            PageDto query = userSendService.query(1, 999, 0, uid, 0, 0);
            if (query.getList() != null && query.getList().size() > 0) {
                List<UserSendDTO> list = (List<UserSendDTO>) query.getList();
                for (UserSendDTO sendDTO : list) {
                    Map user1 = (Map) sendDTO.getUser();
                    builder.append(user1.get("loginName") + "给您发送代理邀请，同意将获得" + sendDTO.getFee() + "元小费；");
                }
            }
            String sendStr = builder.toString();
            user.put("sendStr", sendStr);
            //代理审批数量
            int reviewCount = agentReviewService.queryCount(uid, 0, 0, 0);
            user.put("reviewCount", reviewCount);
            //公司标识
            CompUserExample coex = new CompUserExample();
            CompUserExample.Criteria cocr = coex.createCriteria();
            cocr.andUserIdEqualTo(uid);
            cocr.andStatusEqualTo(1);
            List<CompUser> compUsers = readCompUserDao.selectByExample(coex);
            if (compUsers != null && compUsers.size() > 0) {
                user.put("compId", compUsers.get(0).getCompId());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return user;
    }

    @Override
    public PageDto getAllUser(int pageNum, int rows, int notUid, String order) throws ServiceException {
        PageDto pageDto = new PageDto();
        PageHelper.startPage(pageNum, rows);
        try {
            Map map = new HashMap();
            if (order.contains("1")) { //1支持按粉丝排序
                map.put("fans", 1);
            }
            if (order.contains("2")) {
                map.put("gents", 1);
            }
            if (notUid > 0) {
                map.put("notUid", notUid);
            }
            List<Map> list = rAppLoginDao.qryUserInfoAll(map);
            if (list != null && list.size() > 0) {
                for (Map m : list) {
                    //判断此主页用户是否是你的代理人
                    int count = userAgentService.queryCount(notUid, StringUtil.getInt(m.get("userId"), 0), 0, 1);
                    if (count > 0) {
                        m.put("isAgent", 1);  //1是代理人 0不是
                    } else {
                        m.put("isAgent", 0);
                    }
                    //公司标识
                    CompUserExample coex = new CompUserExample();
                    CompUserExample.Criteria cocr = coex.createCriteria();
                    cocr.andUserIdEqualTo(StringUtil.getInt(m.get("userId"), 0));
                    cocr.andStatusEqualTo(1);
                    List<CompUser> compUsers = readCompUserDao.selectByExample(coex);
                    if (compUsers != null && compUsers.size() > 0) {
                        m.put("compId", compUsers.get(0).getCompId());

                    }
                }
                PageInfo pageInfo = new PageInfo(list);
                pageDto.setInfo(pageInfo);
                pageDto.setList(list);
            }
        } catch (DaoException e) {
            e.printStackTrace();
        }

        return pageDto;
    }
    @Transactional
    @Override
    public int delete(int productId) throws ServiceException {
        int ret = 0;
        try {
            int count = userApplyService.querCount(0, 0, 0, productId, 0, false, false, true, 0, 0);
            if (count > 0) { //判断是否有未处理的申请
                return -998;
            }
            //判断是否为原生产品，为代理产品做处理
            UserProduct product = readUserProductDao.selectByPrimaryKey(productId);
            if (product.getProductType() == 1) { //原生产品
                this.updateAgent(0, productId, 0, 2, 2, -1, -1);
                if (product.getVideoId() > 0) { //原生产品删除视频
                    AttachDTO attach = attachService.sleletById(product.getVideoId());
                    if (attach != null) {
                        try {
                            int i = TecentVideo.delete(attach.getFileId());
                            if (i > 0) {
                                attachService.delete(attach.getAttachId());
                            } else {
                                return -1;
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
                if (product.getGrantNum() > product.getRank() && product.getAgentCost() > 0) { //有剩余的代理费退还
                    BigDecimal cost = new BigDecimal(product.getAgentCost());
                    BigDecimal rank = new BigDecimal(product.getGrantNum() - product.getRank());
                    BigDecimal addAmount = cost.multiply(rank);
                    Map userInfo = new HashMap();
                    //邀请人
                    userInfo.put("userId", product.getSource());
                    Map<String, Object> Uaccount = readAccountDao.qryAccountInfoByUserId(userInfo);
                    userInfo.clear();
                    //邀请人账户
                    userInfo.put("userId", product.getSource());
                    Map<String, Object> Saccount = readAccountDao.qryAccountInfoByUserId(userInfo);

                    //计算代理人的账户金额
                    BigDecimal amount = new BigDecimal(Uaccount.get("amount").toString());
                    BigDecimal nowAmount = amount.add(addAmount);
                    BigDecimal cashAmount = new BigDecimal(Uaccount.get("cashAmount").toString());
                    BigDecimal nowCashAmount = cashAmount.add(addAmount);
                    //代理人账户流水
                    Order order = new Order();
                    String orderId = getOrderId();
                    order.setOrderId(orderId);
                    order.setUserId(Integer.parseInt(Uaccount.get("userId").toString()));
                    order.setAccountId(Integer.valueOf(Uaccount.get("accountId").toString()));
                    order.setAmount(addAmount.doubleValue());
                    order.setGatherAccountId(Integer.valueOf(Saccount.get("accountId").toString()));
                    order.setGatherUserId(Integer.parseInt(Saccount.get("userId").toString()));
                    order.setOrderType("8");//代理费 退回
                    order.setPayType("3");//账户
                    order.setState("13");//冲入
                    writeOrderDao.addOrder(order);
                    Uaccount.put("amount", nowAmount);
                    Uaccount.put("cash_amount", nowCashAmount);
                    writeAccountDao.updateAccount(Uaccount);
                }
            } else if (product.getIsReview() > 0) {
                agentReviewService.delete(product.getProductId());
            }
            ret = writeUserProductDao.deleteByPrimaryKey(productId);
        } catch (DaoException e) {
            e.printStackTrace();
        }
        return ret;
    }
    @Transactional
    @Override
    public PageDto Recommend(int pageNum, int rows, int uid, int type, String province, String city) throws ServiceException {
        PageHelper.startPage(pageNum, rows);
        PageDto pageDto = new PageDto();
        try {
            PageHelper.startPage(pageNum, rows);
            Map map = new HashMap();
            if (!StringUtil.containEmpty(province)) {
                map.put("province", province);
            }
            if (!StringUtil.containEmpty(city)) {
                map.put("city", city);
            }
            map.put("projectType", 1);
            List<UserProduct> userProducts = readUserProductDao.Recommend(map);
            if (userProducts != null && userProducts.size() > 0) {
                List<UserProductDTO> dtos = new ArrayList();
                PageInfo info = new PageInfo(userProducts);
                for (UserProduct product : userProducts) {
                    UserProductDTO dto = null;
                    if (type > 0) {
                        dto = new UserProductDTO();
                        BeanUtils.copyProperties(product, dto);
                    } else {
                        dto = getApplyMax(product);
                    }
                    setExt(dto, uid, false);
                    dtos.add(dto);
                }
                pageDto.setInfo(info);
                pageDto.setList(dtos);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return pageDto;
    }

    /**
     * 获取产品，代理和原产品中申请数量最多
     *
     * @param product
     * @return
     * @throws Exception
     */
    private UserProductDTO getApplyMax(UserProduct product) throws Exception {
        UserProductDTO dto = new UserProductDTO();
        Map map = new HashMap();
        map.put("productId", product.getProductId());
        List<UserProduct> userProducts = readUserProductDao.Recommend(map);
        if (userProducts != null && userProducts.size() > 0) {
            BeanUtils.copyProperties(userProducts.get(0), dto);
        } else {
            BeanUtils.copyProperties(product, dto);
        }
        return dto;
    }
}
